﻿var _page, _silent=true;

function isLogin()
{
	if (ali.util.cookie('UserID') != '' && ali.util.cookie('Namespace') != 'AliCMS.SystemModule')
		return true;
	else
		return false;
}
function login(wxppAppId)
{
	var ref;
	var query = location.search.substr(1);
	var kvps = query.split('&');
	for (var i = 0; i < kvps.length; i++)
	{
		var kvp = kvps[i].split('=');
		if (kvp[0] == 'ref')
		{
			ref = decodeURIComponent(kvp[1]);
			break;
		}
	}

	if (!ref)
		ref = document.location.pathname;

	window.location.replace('https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + wxppAppId + '&redirect_uri=' + encodeURIComponent(window.location.protocol + '//' + window.location.host + '/user/wx_login.html' + '?ref=' + ref) + '&response_type=code&scope=snsapi_userinfo&state=fast#wechat_redirect');
}

//微信浏览器
function isWx(){return navigator.userAgent.indexOf('MicroMessenger') != -1;}
if (isWx())
{
	$('head').append('<script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>');	
}
function initWx(config)
{
	if (!isWx())
		return;
	
	$.getJSON('/alicms.aspx?Lang=' + ali.lang + '&Mark=Course&Object=InstanceConfig&Operation=GetJsApiTicket', function (result)
	{
		try
		{
			if (result.error == 0)
			{
				//某种原因wx为undefined时，重新加载
				if (!wx)
					window.location.reload();

				wx.config(
				{
					appId: result.appId,
					timestamp: result.timestamp,
					nonceStr: result.nonceStr,
					signature: result.signature,
					jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData'],
					openTagList: ['wx-open-audio']
				});
			
				wx.ready(function()
				{
					var ob = {};

					var url = window.location.href;
					if (isLogin())
					{
						if (url.indexOf('?') != -1)
							url = url.substr(0, url.indexOf('?'));
						url += '?DistributerID=' + ali.util.cookie('UserID');

						var q = window.location.search;
						if (q != '')
						{
							var kvps = q.substr(1).split('&');
							for (var i = 0; i < kvps.length; i++)
							{
								var kvp = kvps[i].split('=');
								if (kvp[0] != 'DistributerID')
								{
									url += '&' + kvps[i];
								}
							}
						}
					}
					ob.link = url;
					
					if (config)
					{
						var img = config.imgUrl ? config.imgUrl : '';
						if (img.indexOf('http') != 0)
							img = window.location.protocol + '//' + window.location.host + img;
						ob.imgUrl = img;
	
						ob.title = config.title ? config.title : document.title;
						ob.desc = config.desc ? config.desc : (ali.lang == 'UYG' ? 'بۇ يەردىن تەپسىلاتىنى كۆرۈڭ' : '点此查看详情');

						if (config.onSuccess)
							ob.success = config.onSuccess;

						if (config.onReady)
							config.onReady();
					}
					wx.updateTimelineShareData(ob);
					wx.updateAppMessageShareData(ob);
				});
			}
			else
			{
				ali.toast(ali.lang == 'UYG' ? 'سالون سەپلەنمىگەن!' : '公众号未被配置！');
			}
		}
		catch(e)
		{
			//alert(e.message);
		}
	});
}

function saveDistributer()
{
	var q = window.location.search;
	if (q == '')
		return;

	var kvps = q.substr(1).split('&');
	for (var i = 0; i < kvps.length; i++)
	{
		var kvp = kvps[i].split('=');
		if (kvp[0] == 'DistributerID')
		{
			ali.util.cookie('DistributerID', kvp[1], 24 * 60 , '/');
			return;
		}
	}
}

function isApple()
{
	return navigator.userAgent.match('iPhone|iPad');
}
if (isApple())
	document.addEventListener('touchstart', function () { }, false);
	
//首页
function Index(page)
{
	var __now,
		__page = 1,
		__isEnd = false,
		__isLoading = false,
		__pageSize = 20,
		__list = $('.tab1-body');


	//#region 初始化
	(function ()
	{
	    //存储分享者
	    saveDistributer();

	    //轮换广告
	    var nav = $('.touchslider-navtag');
	    $('.touchslider-viewport').children().each(function (index)
	    {
	        if (index == 0)
	            nav.append('<span class="touchslider-nav-item touchslider-nav-item-current"></span>');
	        else
	            nav.append(' <span class="touchslider-nav-item"></span>');
	    });
	    $('.touchslider').touchSlider({ mouseTouch: true, autoplay: true })
		.on('touchstart', '.touchslider-viewport', function() { $('.touchslider').data('touchslider').stop(); });

		//促销课程
	    if ($('.list2').length)
	    {
			$.get('/alicms.aspx?Mark=System&Object=Utility&Operation=GetServerTime', function (data)
			{
				__now = new Date(data);
				setInterval(updateTime, 1000);
			});
	    }

	    //初始化微信
	    if (isWx())
	    {
			initWx({ desc: null, imgUrl: page.data('logo')});
	    }

		//记录滚动位置，返回时，重新定位
	    var tabBody = $('.tab1-body');
	    if (window.sessionStorage)
	    {
	    	var s = sessionStorage.getItem('index_scroll_top');
	    	if (s)
	    		tabBody[0].scrollTop = s;
	    }
	    tabBody.scroll(function ()
	    {
	    	if (window.sessionStorage)
	    	{
	    		sessionStorage.setItem('index_scroll_top', tabBody[0].scrollTop);
	    	}
	    });

		//加载推荐类别
		$.get(page.data('getRecommendedCategory'), function (result)
		{
			$('.list4').before(result);

			//懒加载
			$('.list5 img[data-src]').lazyLoadXT();
		});

		//内容滚动
		__list.scroll(onListScroll);

		//加载信息
		load(1);
	})();
	//#endregion
	
	function updateTime()
	{
		__now.setSeconds(__now.getSeconds() + 1);
		
		$('.list2 li', page).each(function()
		{
			var start = new Date($(this).data('start')).getTime(),
			end = new Date($(this).data('end')).getTime();
			
			var now = __now.getTime(),
			diff;
			if (now < start)//还没开始
				diff = start - now;
			else//正在进行
				diff = end - now;

			var day = parseInt(diff / (1000 * 60 * 60 * 24));
			var left = diff - day * (1000 * 60 * 60 * 24);
			var hour = parseInt(left / (1000 * 60 * 60));
			left -= hour * (1000 * 60 * 60);
			var minute = parseInt(left / (1000 * 60));
			left -= minute * (1000 * 60);
			var second = parseInt(left / 1000);
			$('b:eq(0)', this).text(day < 10 ? '0' + day : day);
			$('b:eq(1)', this).text(hour < 10 ? '0' + hour : hour);
			$('b:eq(2)', this).text(minute < 10 ? '0' + minute : minute);
			$('b:eq(3)', this).text(second < 10 ? '0' + second : second);
		});
	}

	function load(pageNumber)
	{
		__isLoading = true;
		__page = pageNumber;

		if (__page == 1)
		{
			$('.more', page).text(page.data('loading')).siblings().remove();
		}

		var condition = '?Page=' + __page + '&PageSize=' + __pageSize;
		$.get(page.data('getNewList') + condition, function (data)
		{
			data = $.trim(data);

			if (data != '')
				$('.more', page).before(data);

			var matches = data.match(/<li>/g);
			if (matches == null || matches.length < __pageSize)
			{
				$('.more', page).text(page.data('hasReadAll'));
				__isEnd = true;
			}
			else
			{
				__isEnd = false;
			}
			
			__isLoading = false;

			//懒加载
			$('.more', page).parent().find('img[data-src]').lazyLoadXT();
		});
	}

	function onListScroll()
	{
		if (__isEnd || __isLoading)
			return;

		if (__list[0].scrollHeight - __list[0].clientHeight < this.scrollTop + 10)
		{
			load(++__page);
		}
	}
}

//课程列表
function CourseList(page)
{
	var __page = 1,
		__pageSize = 10,
		__menuBar = $('#course-list-menu-bar');
		__categoryButton = $('li:eq(0)', __menuBar),
		__typeButton = $('li:eq(1)', __menuBar),
		__sortButton = $('li:eq(2)', __menuBar),
		__categoryMenu = $('#course-list-category-menu'),
		__typeMenu = $('#course-list-type-menu'),
		__sortMenu = $('#course-list-sort-menu'),
		__list = $('.tab1-body'),
		__isEnd = false,
		__isLoading = false,
		__menuHeight = __list.height() + $('.tab1-bar').height();

	//#region 初始化
	(function ()
	{
	    //存储分享者
	    saveDistributer();

		//搜索
		$('form button', page).click(onSearchClick);

		//筛选菜单 - 类别
		__categoryButton.click(onCategoryClick);
		//筛选菜单 - 类型
		__typeButton.click(onTypeClick);
		//筛选菜单 - 排序
		__sortButton.click(onSortClick);

		//类别菜单
		__categoryMenu.click(onCategoryMenuBlankClick);
		$('ul', __categoryMenu).on('click', '>li', onCategoryBigItemClick);
		$('>ol', __categoryMenu).on('click', 'li', onCategorySmallItemClick);

		//类型菜单
		__typeMenu.click(onTypeMenuBlankClick);
		$('ul', __typeMenu).on('click', 'li', onTypeItemClick);

		//排序菜单
		__sortMenu.click(onSortMenuBlankClick);
		$('ul', __sortMenu).on('click', 'li', onSortItemClick);

		//内容滚动
	    if (window.sessionStorage && sessionStorage.getItem('course_list_page'))
	    {
			load(parseInt(sessionStorage.getItem('course_list_page')), 'storage');
	    }
	    else
	    {
			__list.scroll(onListScroll);
		
			//
			load(1);
		}
		
		//小程序中，特殊处理首页。因为，点击跳转不了
		$('.tab1-home', page).click(function()
		{
			if (_isWxmp)
			{
				window.location = $(this).attr('href') + '?r=' + Math.random();
				return false;
			}
		});
	})();
	//#endregion

	function hideMenu()
	{
		__categoryMenu.hide();
		__sortMenu.hide();
	}

	function onSearchClick()
	{
		load(1, 'keyword');
		return false;
	}

	function onCategoryClick()
	{
		if (__categoryMenu.is(':hidden'))
		{
			hideMenu();
			$('ul,ol', __categoryMenu).height(__menuHeight - 100);
			__categoryMenu.height(__menuHeight).css({ top: __menuBar.position().top + __menuBar.height() }).fadeIn();
		}
		else
		{
			__categoryMenu.fadeOut();
		}
	}

	function onTypeClick()
	{
		if (__typeMenu.is(':hidden'))
		{
			hideMenu();
			__typeMenu.height(__menuHeight).css({ top: __menuBar.position().top + __menuBar.height() }).fadeIn();
		}
		else
		{
			__typeMenu.fadeOut();
		}
	}

	function onSortClick()
	{
		if (__sortMenu.is(':hidden'))
		{
			hideMenu();
			__sortMenu.height(__menuHeight).css({ top: __menuBar.position().top + __menuBar.height() }).fadeIn();
		}
		else
		{
			__sortMenu.fadeOut();
		}
	}

	function onCategoryMenuBlankClick(e)
	{
		if (e.target == this)
			__categoryMenu.fadeOut();
	}

	function onCategoryBigItemClick()
	{
		if ($(this).hasClass('active'))
			return;
		$(this).addClass('active').siblings().removeClass('active');

		var smallItems = $('>ol', __categoryMenu);
		smallItems.find('li:gt(0)').remove().end().append($('ol', this).html()).children().removeClass('active');

		//如果没有子类，则直接加载
		if (smallItems.children().length == 1)
			smallItems.find('li:eq(0)').click();
	}

	function onCategorySmallItemClick()
	{
		if ($(this).hasClass('active'))
			return;
		$(this).addClass('active').siblings().removeClass('active');

		if ($(this).data('id') == '')
		{
			var parent = $('ul>li.active', __categoryMenu)
			if (parent.data('id') == '')
			{
				__categoryButton.text(page.data('categoryText'));
				page.data('categoryId', '');
			}
			else
			{
				__categoryButton.text($('a', parent).text());
				page.data('categoryId', parent.data('id'));
			}
		}
		else
		{
			page.data('categoryId', $(this).data('id'));
			__categoryButton.text($(this).text());
		}
		__categoryMenu.fadeOut();

		load(1, 'category');
	}

	function onTypeMenuBlankClick(e)
	{
		if (e.target == this)
			__typeMenu.fadeOut();
	}

	function onTypeItemClick()
	{
		if ($(this).hasClass('active'))
			return;
		$(this).addClass('active').siblings().removeClass('active');

		page.data('type', $(this).data('id'));
		if ($(this).data('id') == '')
			__typeButton.text(page.data('typeText'));
		else
			__typeButton.text($(this).text());
		__typeButton.text($(this).text());
		__typeMenu.fadeOut();

		load(1, 'type');
	}

	function onSortMenuBlankClick(e)
	{
		if (e.target == this)
			__sortMenu.fadeOut();
	}

	function onSortItemClick()
	{
		if ($(this).hasClass('active'))
			return;
		$(this).addClass('active').siblings().removeClass('active');

		page.data('order', $(this).data('id'));
		if ($(this).data('id') == '')
			__sortButton.text(page.data('orderText'));
		else
			__sortButton.text($(this).text());
		__sortButton.text($(this).text());
		__sortMenu.fadeOut();

		load(1, 'sort');
	}

	function load(pageNumber, from)
	{
		__isLoading = true;
		if (from == 'storage')
			__page = 1;
		else
			__page = pageNumber;

		var categoryId = page.data('categoryId'),
			type = page.data('type'),
			order = page.data('order'),
			q = encodeURIComponent($('form input', page).val());
		if (__page == 1)
		{
			$('.more', page).text(page.data('loading')).siblings().remove();
			
			if (from == 'category' || from == 'type' || from == 'sort' || from == 'keyword')
			{
				var url = page.data('tpl').replace('{CategoryID}', categoryId == '' ? '_' : '_' + categoryId).replace('{Type}', type == '' ? '_' : '_' + type).replace('{Order}', order == '' ? '_' : '_' + order).replace('{q}', q == '' ? '_' : '_' + q);
				history.pushState(null, '', url);
			}
		}

		var condition = '?Page=' + __page + '&PageSize=' + (from == 'storage' ? pageNumber * __pageSize : __pageSize) + '&CategoryID=' + categoryId + '&MediaType=' + type + '&Order=' + order + '&Keyword=' + q;
		$.get(page.data('path') + condition, function (data)
		{
			data = $.trim(data);

			if (data != '')
				$('.more', page).before(data);

			var matches = data.match(/<li>/g);
			if (matches == null || matches.length < 10)
			{
				$('.more', page).text(page.data('hasReadAll'));
				__isEnd = true;
			}
			else
			{
				__isEnd = false;
			}
			
			__isLoading = false;
			
			//懒加载
			$('.more', page).parent().find('img[data-src]').lazyLoadXT();

			//记录滚动位置
			if (window.sessionStorage)
			{
				if (from == 'storage')
				{
					__page = pageNumber;
					__list[0].scrollTop = sessionStorage.getItem('course_list_scroll_top');
					__list.scroll(onListScroll);
				}
				else
				{
	    			sessionStorage.setItem('course_list_page', __page);
				}
			}
		});
	}

	function onListScroll()
	{
		//记录滚动位置
	    if (window.sessionStorage)
	    {
	    	sessionStorage.setItem('course_list_scroll_top', this.scrollTop);
	    }

		if (__isEnd || __isLoading)
			return;

		if (this.scrollHeight - this.clientHeight < this.scrollTop + 10)
		{
			load(++__page);
		}
	}
}

//课程详情
function CourseView(page)
{
	var __promotion,
		__isMemberPay = false,
		__price = page.data('price'),
		__sum = __price,
		__memberPrice = 0,
		__userNickname,
		__userHead,
		__distributerId,
		__distributerName,
		__distributerNickname,
		__distributerHead,
		__distributerIsAgent,
		__agentCommision,
		__paymentId,
		__now,
		__courseStudy,
		__courseFree = false,
		__hasBuy = false,
		__lesson,
		__media,
		__lastUpdate = (new Date()).getTime();

	//#region 初始化
	(function ()
	{
	    //存储分享者
		saveDistributer();

		//强制登陆
		if (!isLogin())
		{
			login(page.data('wxppAppId'));
			return;
		}

		//分享
		$('#distribute,.share').click(onShareClick);
		$('.block13').click(onQRCodePanelClick);	

		//滚动时，tab2-bar浮动或固定
		$('.tab2-bar a').click(onTab2BarClick);
		var tab2Top = $('.tab2-bar').offset().top;
	    $('.tab1-body').scroll(function ()
	    {
	    	var scrollTop = $(this).scrollTop();
			if (scrollTop >= tab2Top)
				$('.tab2-content').css('overflow-y', 'auto');
			else
				$('.tab2-content').css('overflow-y', 'hidden');
	    });

		//点击课件
		$('#course-view-lesson-list dd').click(onLessonClick);

		//
		var q = '?CourseID=' + page.data('guid') + '&CourseName=' + encodeURIComponent($('.titlebar h1').text()) + '&CourseThumbnail=' + encodeURIComponent(page.data('picture')) + '&IsMemberFree=' + page.data('isMemberFree') + '&Price=' + page.data('price');
		var hasDistributer = ali.util.cookie('DistributerID') != '' && ali.util.cookie('UserID') != ali.util.cookie('DistributerID');
		if (hasDistributer)
			q += '&DistributerID=' + ali.util.cookie('DistributerID');
		$.getJSON(page.data('path') + q, function (result)
		{
			$('#wait').hide();

			if (parseFloat(page.data('price')) == 0)
			{
				__courseFree = true;
				$('#home,#collect,#distribute').css('flex', '1').show();
			}
			else
			{
				if (result.hasBuy)
				{
					__hasBuy = true;
					if (result.days)
						$('#expired-time').show().find('span').text(page.data('expiredTime').replace('{days}', result.days));
					$('#home,#collect,#distribute,#study').show();

					__courseStudy = result.courseStudy;
					if (__courseStudy.startTime != '')
						$('#study').text(page.data('continue'));
					$('#study').click(onStudyClick);

					//评价
					$('#course-view-ask').submit(onAskSubmit);
				}
				else
				{
					__userNickname = result.userNickname;
					__userHead = result.userHead;
					__distributerId = result.distributerId;
					__distributerName = result.distributerName;
					__distributerNickname = result.distributerNickname;
					__distributerHead = result.distributerHead;
					__distributerIsAgent = result.distributerIsAgent;
					__agentCommision = result.agentCommision;
					__paymentId = result.paymentId;
					if (result.isMemberPay)//会员支付
					{
						__isMemberPay = true;
						__memberPrice = result.memberPrice;
						//__agentCommision = __memberPrice * __agentCommision / 100;
						__sum = __memberPrice;
						$('#member-buy p em').text(result.memberCommission);
						$('#member-buy i em').text(__memberPrice);
						$('#member-buy').css('display', 'flex').click(onPayClick);
					}
					else if (result.promotion)//限时促销
					{
						__promotion = result.promotion;
						//__agentCommision = __promotion.price * __agentCommision / 100;
						__sum = __promotion.price;
						$('#promotion em').text(__promotion.price);
						__now = new Date(result.now);//当前时间
						setInterval(updateTime, 1000);
						$('#promotion').css('display', 'flex').click(onPayClick);
					}
					else//立即购买
					{
						$('#buy').css({flex:'5',display:'block'}).click(onPayClick);
						$('#collect').css({flex:'1',display:'block'});
					}
				}
			}

			//初始化微信
			initWx({ imgUrl: page.data('picture') });

			//收藏
			$('#collect').click(onCollectClick);
			if (result.collectId)
				$('#collect').addClass('collected').data('id', result.collectId).text(page.data('alreadyCollect'));

			//完成
			$('#playing').on('click', '.finish', function () { ali.confirm(page.data('confirmFinish'), function (value) { if (value) { finish(); } }); });

			//评价数
			$('#course-view-count em:eq(2)').text(result.askCount);
		});

		//增加人气
		$.post('/alicms.aspx?Lang=' + ali.lang + '&Mark=Course&Object=Course&Operation=IncrementHitCount&ID=' + page.data('id'), {});
	})();
	//#endregion

	function onTab2BarClick()
	{
		if ($(this).hasClass('active'))
			return;

		$(this).addClass('active').siblings().removeClass('active');

		var index = $(this).parent().children().index(this);
		var content = $(this).parent().next().children().eq(index);
		content.addClass('active').siblings().removeClass('active');
	}

	function onShareClick()
	{
		var panel = $('.block13');
		if ($('img', panel).length == 0)
		{
			ali.working(ali.dict('working'));

			var logo = page.data('picture');
			var url = window.location.href;
			if (url.indexOf('?') != -1)
				url = url.substr(0, url.indexOf('?'));
			if (isLogin())
				url += '?DistributerID=' + ali.util.cookie('UserID');
			$.get('/alicms.aspx?Mark=Course&Object=InstanceConfig&Operation=BuildQRCode&Text=' + encodeURIComponent(url) + '&Logo=' + encodeURIComponent(logo), function (qrPath)
			{
				if (qrPath == '')
				{
					ali.working();
					ali.toast(ali.dict('operation_fail'));
				}
				else
				{
					imageFromHtml(panel, qrPath);
				}
			});
		}
		else
		{
			if (panel.is(':hidden'))
				panel.css('display', 'flex');
			else
				pannel.hide();
		}
	}

	function imageFromHtml(panel, qrPath)
	{
		$('.qr').attr('src', qrPath);
		html2canvas($('#course-view-share-html .frame')[0]).then(function(canvas)
		{
			ali.working();
	
			panel.html('<img src="' + canvas.toDataURL() + '"><dl><dt><img src="' + qrPath + '"></dt><dd>' + page.data('saveImage') + '</dd></dl>').css('display', 'flex');
		});
	}

	function onQRCodePanelClick(e)
	{
		if (e.target == this)
			$(this).hide();
	}

	function onCollectClick()
	{
		ali.working(ali.dict('working'));

		var me = $(this);
		if ($(this).hasClass('collected'))
		{
			$.get('/alicms.aspx?Lang=' + ali.lang + '&Mark=Course&Object=Collect&Operation=GetInnerIDFromGuid&ID=' + me.data('id'), function (result)
			{
				$.ajax(
				{
					url: '/alicms.aspx?Lang=' + ali.lang + '&Mark=Course&Object=Collect&Operation=Delete&ID=' + result,
					data: {},
					type: 'POST',
					error: function ()
					{
						ali.working();
						ali.toast(ali.dict('operation_fail'));
					},
					success: function ()
					{
						ali.working();
						me.removeClass('collected').removeData('id').text(page.data('collect'));
						ali.toast(ali.dict('operation_success'));
					}
				});
			});
		}
		else
		{
			//准备数据
			var data = 'CourseID=' + page.data('guid');
			data += '&UserID=' + ali.util.cookie('UserID');
		
			//提交数据
			$.ajax(
			{
				url: '/alicms.aspx?Lang=' + ali.lang + '&Mark=Course&Object=Collect&Operation=Add',
				data: data,
				type: 'POST',
				error: function()
				{
					ali.working();
					ali.toast(ali.dict('operation_fail'));
				},
				success: function(guid)
				{
					ali.working();
					me.addClass('collected').data('id', guid).text(page.data('alreadyCollect'));
					ali.toast(ali.dict('operation_success'));
				}
			});
		}
	}

	function updateTime()
	{
		__now.setSeconds(__now.getSeconds() + 1);

		var now = __now.getTime();
		var row = $('#promotion');
		var start = new Date(__promotion.startTime).getTime();
		var end = new Date(__promotion.endTime).getTime();

		//（1）未开始->开始2秒钟内；（2）正在进行->结束2秒钟内，刷新页面
		if (now >= start && now - start < 2000 || end >= now && end - now < 2000)
		{
			window.location.reload();
			return;
		}

		var diff;
		if (now < start)//还没开始
			diff = start - now;
		else if (now < end)//正在进行
			diff = end - now;
		else//已结束
			return;

		var day = parseInt(diff / (1000 * 60 * 60 * 24));
		var left = diff - day * (1000 * 60 * 60 * 24);
		var hour = parseInt(left / (1000 * 60 * 60));
		left -= hour * (1000 * 60 * 60);
		var minute = parseInt(left / (1000 * 60));
		left -= minute * (1000 * 60);
		var second = parseInt(left / 1000);
		$('b:eq(0)', row).text(day < 10 ? '0' + day : day);
		$('b:eq(1)', row).text(hour < 10 ? '0' + hour : hour);
		$('b:eq(2)', row).text(minute < 10 ? '0' + minute : minute);
		$('b:eq(3)', row).text(second < 10 ? '0' + second : second);
	}

	function onStudyClick()
	{
		if ($(this).hasClass('disabled'))
			return;
		$(this).addClass('disabled');

		if (__courseStudy.startTime == '')//开始学习
		{
			$.ajax(
			{
				url: '/alicms.aspx?Lang=' + ali.lang + '&Mark=Course&Object=CourseStudy&Operation=Start&ID=' + __courseStudy.id,
				data: {},
				type: 'POST',
				error: function()
				{
					ali.working();
					ali.toast(ali.dict('operation_fail'));
				},
				success: function(result)
				{
					result = JSON.parse(result);
					__courseStudy.startTime = result.startTime;
					__courseStudy.max = result.max;

					if (__courseStudy.lastLessonId == '')
						$('#course-view-lesson-list dd:eq(0)').click();
					else
						$('#course-view-lesson-list [data-id=' + __courseStudy.lastLessonId + ']').click();
				}
			});
		}
		else//继续学习
		{
			if (__courseStudy.lastLessonId == '' || __courseStudy.lastLessonId == '0')
				$('#course-view-lesson-list dd:eq(0)').click();
			else
				$('#course-view-lesson-list [data-id=' + __courseStudy.lastLessonId + ']').click();
		}
	}

	function onLessonClick()
	{
		var me = $(this);
		if (me.hasClass('active'))
			return;

		if (!isLogin())
		{
			login(page.data('wxppAppId'));
			return;
		}

		//未购买，不免费
		var isFree = me.find('b').length > 0;
		if (!__courseFree && !__hasBuy && !isFree)
		{
			ali.toast(page.data('notBuy'));
			return;
		}

		//已购买，未开始
		if (__hasBuy && __courseStudy.startTime == '')
		{
			__courseStudy.lastLessonId = me.data('id');
			onStudyClick();
			return;
		}

		if (page.data('mediaType') == 'TEXT')
		{
			window.location = page.data('textPath') + '?CourseID=' + page.data('id') + '&LessonID=' + me.data('id') + (__courseStudy ? '&CourseStudyID=' + __courseStudy.id : '');
		}
		else
		{
			ali.working(ali.dict('working'));

			//获取课件信息
			$.getJSON(page.data('getLesson') + '?ID=' + me.data('id') + '&HasBuy=' + __hasBuy, function (result)
			{
				__lesson = result;
	
				if (__hasBuy)
				{
					//更新课程学习中，最后学习的课件
					$.post('/alicms.aspx?Lang=' + ali.lang + '&Mark=Course&Object=CourseStudy&Operation=UpdateLastLessonID&ID=' + __courseStudy.id + '&LastLessonID=' + me.data('id'));
	
					//更新课件人气
					$.post('/alicms.aspx?Lang=' + ali.lang + '&Mark=Course&Object=Lesson&Operation=IncrementHitCount&ID=' + __lesson.innerId, {});
	
					//如果课件没开始学习，则开始
					if (__lesson.study)
					{
						ali.working();
						play(me);
					}
					else
					{
						$.ajax(
						{
							url: '/alicms.aspx?Lang=' + ali.lang + '&Mark=Course&Object=LessonStudy&Operation=Add',
							data: 'CourseID=' + page.data('guid') + '&LessonID=' + __lesson.id + '&Max=' + __lesson.duration,
							type: 'POST',
							error: function()
							{
								ali.working();
								ali.toast(ali.dict('operation_fail'));
							},
							success: function(guid)
							{
								$.get('/alicms.aspx?Lang=' + ali.lang + '&Mark=Course&Object=LessonStudy&Operation=GetInnerIDFromGuid&ID=' + guid, function (result)
								{
									__lesson.study = { id: result, value: 0, max: __lesson.duration, startTime: ali.util.formatDate(new Date(), 'yyyy-MM-dd'), endTime: '' };
	
									ali.working();
									play(me);
								});
							}
						});
					}
	
					//允许评价
					var askSubmit = $('#course-view-ask [type=submit]');
					if (askSubmit.hasClass('disabled'))
						askSubmit.removeClass('disabled').prop('disabled', false);
				}
				else
				{
					ali.working();
					play(me);
				}
	
				//写入当前课件的信息
				$('#course-view-lesson-info').show().find('dt').text(__lesson.name).next().html(__lesson.description);
	
				//加载评论
				$.get(page.data('getAskList') + '?LessonID=' + __lesson.id, function (askList)
				{
					var ask = $('.list11').find('ul').remove().end();
					if ($.trim(askList) != '')
					{
						ask.children('h1').after(_btoE ? bToE(askList) : askList);
						ask.children('p').hide();
					}
					else
					{
						ask.children('p').show();
					}
				});
			});
		}
	}

	function play(me)
	{
		//设为选中
		$('#course-view-lesson-list dd').removeClass('active');
		me.addClass('active');

		//写入播放器
		var html;
		if (__lesson.mediaType == 'AUDIO')
		{
			html = $('#player audio');
			if (html.length > 0)
			{
				html.attr('src', __lesson.url);

				const audio = document.getElementById('audio');
				audio.src = __lesson.url;
				audio.title = __lesson.name;
				audio.episode = page.data('name');
				audio.cover = page.data('picture');
			}
			else
			{
				html = $('<audio src="' + __lesson.url + '" controlsList="nodownload" controls="true" autoplay="autoplay"></audio><wx-open-audio id="audio" src="' + __lesson.url + '" title="=' + __lesson.name + '" episode="' + page.data('name') + '" cover="' + page.data('picture') + '"></wx-open-audio>');
				$('#player').html(html);

				//设置事件
				html.eq(0).on('ended', onMeidaEnded)
								.on('canplay', onMediaCanPlay)
								.on('timeupdate', onMediaTimeUpdate);
				
				const audio = document.getElementById('audio');
				audio.addEventListener('timeupdate', (e) => 
				{
					__media.currentTime = e.detail.currentTime;
					onMediaTimeUpdate();
				});
				audio.addEventListener('seeked', (e) => 
				{
					__media.currentTime = e.detail.currentTime;
					onMediaTimeUpdate();
				});
				audio.addEventListener('ended', (e) => 
				{
					onMeidaEnded();
				});
			}
		
			html[0].load();
			html[0].play();
		}
		else
		{
			html = $('<video src="' + __lesson.url + '" controlsList="nodownload" controls="true" autoplay="autoplay" playsinline="true" webkit-playsinline="true" x5-playsinline="true" x-webkit-airplay="allow"></video>');
			$('#player').html(html);

			//设置事件
			html.on('ended', onMeidaEnded)
				.on('play', onMediaPlay)
				.on('timeupdate', onMediaTimeUpdate);
		}

		//滑动到顶端
		$('#course-view-body').animate({scrollTop:0}, 500);

		//全局媒体设置
		__media = html[0];

		//显示当前课件
		if (__hasBuy)
		{
			$('#study').hide();
			$('#playing').find('em').text(page.data('lessonNo').replace('{1}', ali.lang == 'CHS' ? me.find('i').text().replace('.', '') : me.find('i').text())).next().removeClass('finish').addClass(__lesson.study.endTime == '' ? 'finish' : 'finished').text(__lesson.study.endTime == '' ? page.data('finish') : page.data('finished')).end().end().show();
		}
	}

	function onMediaCanPlay()
	{
		if (__lesson.study && __media.duration - __lesson.study.value > 60)
			__media.currentTime = __lesson.study.value;

		$(__media).off('canplay');
	}

	function onMeidaEnded()
	{
		next();
	}

	function onMediaTimeUpdate()
	{
		if (__lesson.study && __lesson.study.endTime == '')
		{
			var now = (new Date()).getTime();
			if (now - __lastUpdate < 60000)
				return;

			__lastUpdate = now;
			__lesson.study.value = parseInt(__media.currentTime);
			$.ajax(
			{
				url: '/alicms.aspx?Lang=' + ali.lang + '&Mark=Course&Object=LessonStudy&Operation=Modify&ID=' + __lesson.study.id,
				data: 'Value=' + __lesson.study.value,
				type: 'POST',
				error: function()
				{
				},
				success: function(result)
				{
				}
			});
		}
		
		//没有购买，免费试用，检查是否超出
		if (!__courseFree && !__hasBuy && __lesson.freeDuration > 0 && __media.currentTime > __lesson.freeDuration)
		{
			__media.currentTime = __lesson.freeDuration;
			__media.pause();
			ali.alert(page.data('outOfFree'), { modal: true });
		}
	}

	function finish()
	{
		$.ajax(
		{
			url: '/alicms.aspx?Lang=' + ali.lang + '&Mark=Course&Object=LessonStudy&Operation=Finish&ID=' + __lesson.study.id,
			data: {},
			type: 'POST',
			error: function()
			{
				ali.working();
				ali.toast(ali.dict('operation_fail'));
			},
			success: function(result)
			{
				$('.finish').removeClass('finish').addClass('finished').text(page.data('finished'));

				next();
			}
		});
	}

	function next()
	{
		//播放下一个
		var lessons = $('#course-view-lesson-list dd');
		var lesson = lessons.filter('[data-id=' + __lesson.innerId + ']');
		var index = lessons.index(lesson);
		if (index < lessons.length)
			lessons.eq(index + 1).click();
	}

	function onAskSubmit()
	{
		ali.working(ali.dict('working'));

		//准备数据
		var data = 'CourseID=' + page.data('guid');
		data += '&LessonID=' + __lesson.id;
		data += '&Anchor=' + parseInt(__media.currentTime);
		data += '&Content=' + encodeURIComponent(this.Content.value);
		
		//提交数据
		$.ajax(
		{
			url: '/alicms.aspx?Lang=' + ali.lang + '&Mark=Course&Object=Ask&Operation=Add',
			data: data,
			type: 'POST',
			error: function()
			{
				ali.working();
				ali.toast(ali.dict('operation_fail'));
			},
			success: function(guid)
			{
				ali.working();
				ali.toast(page.data('needCheck'));
			}
		});

		return false;
	}

	function onPayClick()
	{
		if ($(this).hasClass('disabled'))
			return false;
		$(this).addClass('disabled');

		//金额要大于零
		if (__sum <= 0)
		{
			ali.toast(page.data('sumIncorrect'));
			return;
		}

		//准备数据
		var data = 'CourseID=' + page.data('guid');
		data += '&CourseName=' + encodeURIComponent(page.data('name'));
		data += '&CourseThumbnail=' + encodeURIComponent(page.data('picture'));
		data += '&TimeUnit=' + page.data('timeUnit');
		data += '&TimeAmount=' + page.data('timeAmount');
		data += '&UserID=' + ali.util.cookie('UserID');
		data += '&UserName=' + ali.util.cookie('UserName');
		data += '&UserNickname=' + encodeURIComponent(__userNickname);
		data += '&UserHead=' + encodeURIComponent(__userHead);

		var income = __sum;
		if (page.data('teacherId'))
		{
			var teacherCommision = income * parseFloat(page.data('teacherCommision')) / 100;
			data += '&TeacherID=' + page.data('teacherId');
			data += '&TeacherName=' + page.data('teacherName');
			data += '&TeacherHead=' + page.data('teacherHead');
			data += '&TeacherCommision=' + teacherCommision.toFixed(2);

			income = __sum - teacherCommision;
		}

		if (__distributerId)
		{
			data += '&DistributerID=' + __distributerId;
			data += '&DistributerName=' + __distributerName;
			data += '&DistributerNickname=' + encodeURIComponent(__distributerNickname);
			data += '&DistributerHead=' + encodeURIComponent(__distributerHead);
			if (__distributerIsAgent)
			{
				data += '&DistributerIsAgent=true';
				data += '&AgentCommision=' + (income * __agentCommision / 100).toFixed(2);
			}
		}

		if (__promotion)
			data += '&Promotion=' + encodeURIComponent(JSON.stringify(__promotion));

		data += '&Price=' + __price.toFixed(2);
		data += '&Sum=' + __sum.toFixed(2);

		ali.working(ali.dict('working'));

		$.ajax(
		{
			url: '/alicms.aspx?Lang=' + ali.lang + '&Mark=Course&Object=Order&Operation=Add',
			data: data,
			type: 'POST',
			error: function ()
			{
				ali.toast(ali.dict('operation_fail'));
				ali.working();
			},
			success: function (guid)
			{
				//准备数据
				var data = 'Title=' + encodeURIComponent(page.data('name'));
				data += '&Amount=' + __sum;
				data += '&PaymentID=' + __paymentId;
				data += '&ReturnUrl=' + encodeURIComponent(page.data('payReturnUrlPath'));

				$.ajax(
				{
					url: '/alicms.aspx?Lang=' + ali.lang + '&Mark=Course&Object=Order&Operation=OnlinePayRequest&ID=' + guid,
					data: data,
					type: 'POST',
					error: function ()
					{
						ali.toast(ali.dict('operation_fail'));
						ali.working();
					},
					success: function (data)
					{
						$('body').append('<div style="display:none">' + data + '</div>').find('form:last').submit();
					}
				});
			}
		});
	}
}

//图文内容页
function LessonText(page)
{
	var __all,
		__hasBuy,
		__courseFree = false,
		__courseStudyId,
		__lessons = [],
		__indexWrap = $('#lesson-text-index .wrap'),
		__indexBody = $('#lesson-text-index .body');

	//#region 初始化
	(function ()
	{
		var path = page.data('path') + '?CourseID=' + page.data('guid') + '&CourseStudyID=' + page.data('courseStudyId') + '&IsMemberFree=' + page.data('isMemberFree');
		if (page.data('courseStudyId') != "")
			path += '&CourseName=' + encodeURIComponent(page.data('name')) + '&CourseThumbnail=' + encodeURIComponent(page.data('picture')) + '&InstanceID=' + page.data('instanceId') + '&SubInstanceID=' + page.data('subInstanceId');
		$.getJSON(path, function (result)
		{
			__all = result.lessons;
			__hasBuy = result.hasBuy;
			__courseStudyId = result.courseStudyId;

			if (parseFloat(page.data('price')) == 0)
				__courseFree = true;

			//调整ParentID，并添加lessons
			var chapterId = null;
			for (var i in __all)
			{
				var lesson = __all[i];
				if (lesson.IsChapter)
				{
					lesson.ParentID = '';
					chapterId = lesson.ID;
				}
				else
				{
					if (chapterId != null)
						lesson.ParentID = chapterId;
					else
						lesson.ParentID = '';

					__lessons.push(lesson);
				}
			}

			//
			$('#prev').click(onPrevClick);
			$('#next').click(onNextClick);
			$('#list').click(onListClick);
			$('#lesson-text-index').on('click', 'h1 a', onIndexBackClick)
							 .on('click', 'dd', onIndexItemClick);
			$('.block8').click(onBlankClick);

			//
			getLesson(page.data('lessonId'));

			//初始化微信
			initWx({ companyId: page.data('companyId'), desc: null, imgUrl: page.data('picture') });
		});
	})();
	//#endregion

	function getLesson(id)
	{
		ali.working(ali.dict('working'));

		//
		var lesson;
		for (var i = 0; i <  __lessons.length; i++)
		{
			if (__lessons[i].ID == page.data('lessonId'))
			{
				lesson = __lessons[i];
				break;
			}
		}

		//未购买或不免费
		if (!__courseFree && !__hasBuy && !lesson.isFree)
		{
			document.title = lesson.Name;
			$('#lesson-text-body>h1').text(lesson.Name);
			$('#lesson-text-body>p>span').text(0);
			$('#lesson-text-body>div').html(page.data('notBuy'));

			//第一个
			if (__lessons[0].ID == id)
				$('#prev').addClass('disabled');
			else
				$('#prev').removeClass('disabled');

			//最后一个
			if (__lessons[__lessons.length - 1].ID == id)
				$('#next').addClass('disabled');
			else
				$('#next').removeClass('disabled');

			ali.working();
		}
		else//已购买或免费
		{
			$.getJSON(page.data('getLesson') + '?ID=' + id, function (result)
			{
				document.title = result.name;
				$('#lesson-text-body>h1').text(result.name);
				$('#lesson-text-body>p>span').text(result.hitCount);
				$('#lesson-text-body>div').html(result.description);

				if (__hasBuy && page.data('courseStudyId') != '')
				{
					//更新课程学习中，最后学习的课件
					$.post('/alicms.aspx?Lang=' + ali.lang + '&Mark=Course&Object=CourseStudy&Operation=UpdateLastLessonID&ID=' + page.data('courseStudyId') + '&LastLessonID=' + result.id);
				}

				//更新课件人气
				$.post('/alicms.aspx?Lang=' + ali.lang + '&Mark=Course&Object=Lesson&Operation=IncrementHitCount&ID=' + result.innerId, {});

				//第一个
				if (__lessons[0].ID == id)
					$('#prev').addClass('disabled');
				else
					$('#prev').removeClass('disabled');

				//最后一个
				if (__lessons[__lessons.length - 1].ID == id)
					$('#next').addClass('disabled');
				else
					$('#next').removeClass('disabled');

				ali.working();
			});
		}
	}

	function onPrevClick()
	{
		if ($(this).hasClass('disabled'))
			return;

		for (var i = 0; i <  __lessons.length; i++)
		{
			if (__lessons[i].ID == page.data('lessonId'))
			{
				var id = __lessons[i - 1].ID;
				page.data('lessonId', id);
				getLesson(id);
				return;
			}
		}
	}

	function onNextClick()
	{
		if ($(this).hasClass('disabled'))
			return;

		for (var i = 0; i <  __lessons.length; i++)
		{
			if (__lessons[i].ID == page.data('lessonId'))
			{
				var id = __lessons[i + 1].ID;
				page.data('lessonId', id);
				getLesson(id);
				return;
			}
		}
	}

	function onListClick()
	{
		$('#lesson-text-index .frame').removeClass('out');
		$('#lesson-text-index').show();

		if (__indexBody.is(':empty'))
		{
			var html = '<dl style="width:' + __indexWrap.width() + 'px;height:' +  + __indexWrap.height() + 'px">';
			for (var i in __all)
			{
				if (__all[i].IsChapter)
					html += '<dt>' + __all[i].Name + '</dt>';
				else
					html += '<dd data-id="' + __all[i].ID + '">' + __all[i].Name + '</dd>';
			}
			html += '</dl>';
			__indexBody.html(html);
			__indexBody.width(__indexWrap.width());
		}
	}
	function onIndexBackClick()
	{
		hideMenu($(this).parent().parent().parent());
	}
	function onIndexItemClick()
	{
		page.data('lessonId', $(this).data('id'));
		getLesson($(this).data('id'));

		//选中
		$(this).parent().find('.active').removeClass('active');
		$(this).addClass('active');

		//关闭
		hideMenu($('#lesson-text-index'));
	}
	function onBlankClick(e)
	{
		if (e.target == this)
			hideMenu(this);
	}
	function hideMenu(menu)
	{
		$('.frame', menu).addClass('out');
		setTimeout(function () { $(menu).hide();}, 500);
	}
}

//课程 - 支付结果
function CoursePayReturnUrl(page)
{
	//#region 初始化
	(function ()
	{
		//判断是否出错
		var params = page.data('params');
		if (params.error)
		{
			alert(params.errmsg);
			window.location.replace(page.data('coursePath'));
			return;
		}

		//微信JS Api准备事件
		if (typeof(WeixinJSBridge) == 'undefined')
		{
			if (document.addEventListener)
			{
				document.addEventListener('WeixinJSBridgeReady', onWeixinJSBridgeReady, false);
			}
			else if (document.attachEvent)
			{
				document.attachEvent('WeixinJSBridgeReady', onWeixinJSBridgeReady);
				document.attachEvent('onWeixinJSBridgeReady', onWeixinJSBridgeReady);
			}
		}
		else
		{
			onWeixinJSBridgeReady();
		}
	})();
	//#endregion

	function onWeixinJSBridgeReady()
	{
		WeixinJSBridge.invoke('getBrandWCPayRequest', page.data('params'), function(result)
		{
			if (result.errMsg && result.errMsg.indexOf('fail') != -1)
			{
				alert(JSON.stringify(result) + '\r\n' + JSON.stringify(page.data('params')));
				window.location.replace(page.data('coursePath'));
			}

			if (result.err_msg.indexOf('ok') != -1)
			{
				window.location.replace(page.data('coursePath'));
			}
			else if (result.err_msg.indexOf('cancel') != -1)
			{
				window.location.replace(page.data('coursePath'));
			}
			else
			{
				alert(JSON.stringify(result) + '\r\n' + JSON.stringify(page.data('params')));
				window.location.replace(page.data('coursePath'));
			}
		});
	}
}

//教师中心 - 首页
function TeacherIndex(page)
{
	var __teacherId;

	//#region 初始化
	(function ()
	{
		if (isLogin())
		{
			//头像
			$.getJSON(page.data('path'), function (result)
			{
				$('#user-head', page).attr('src', result.head);

				if (!result.name)//不是教师
				{
					$('#apply').css('display', 'flex').find('label').text(result.nickname != '' ? result.nickname : result.userName);
				}
				else if (result.isChecked != 1)
				{
					var state;
					if (result.isChecked == 0)
						state = page.data('waitCheck');
					else
						state = page.data('notCheck');

					$('#state').show().find('label').text(_btoE ? bToE(result.name) : result.name).end().find('b').text(_btoE ? bToE(state) : state);
				}
				else
				{
					__teacherId = result.teacherId;
					$('#teacher-home a').attr('href', $('#teacher-home a').attr('href').replace('{ID}', result.teacherInnerId));

					$('#balance em').text(result.balance);
					$('#balance').attr('href', getPlatformUrl() + 'company/user_money/list.html?CompanyID=' + page.data('companyId'));
					$('#money-stat a').attr('href', getPlatformUrl() + 'company/user_money/stat.html?CompanyID=' + page.data('companyId'));

					$('#user-name').text(_btoE ? bToE(result.name) : result.name).show();
					$('#head>h2,#nav').css('display', 'flex');

					var now = new Date();

					//今日订单
					var start = encodeURIComponent(ali.util.formatDate(now, 'yyyy-MM-dd 00:00:00'));
					var end = encodeURIComponent(ali.util.formatDate(now, 'yyyy-MM-dd 23:59:59'));
					$.getJSON('/alicms.aspx?Lang=' + ali.lang + '&Mark=Course&Object=Order&Operation=SubSite_Teacher_StatOne&SubInstanceID=' + page.data('subInstanceId') + '&TeacherID=' + __teacherId + '&Start=' + start + '&End=' + end, function (result)
					{
						$('#today b').text(result.Count);
					});

					//本月订单
					start = encodeURIComponent(ali.util.formatDate(now, 'yyyy-MM-01 00:00:00'));
					end = encodeURIComponent(ali.util.formatDate(now, 'yyyy-MM-dd 23:59:59'));
					$.getJSON('/alicms.aspx?Lang=' + ali.lang + '&Mark=Course&Object=Order&Operation=SubSite_Teacher_StatOne&SubInstanceID=' + page.data('subInstanceId') + '&TeacherID=' + __teacherId + '&Start=' + start + '&End=' + end, function (result)
					{
						$('#month b').text(result.Count);
					});

					//全部订单
					$.getJSON('/alicms.aspx?Lang=' + ali.lang + '&Mark=Course&Object=Order&Operation=SubSite_Teacher_StatOne&SubInstanceID=' + page.data('subInstanceId') + '&TeacherID=' + __teacherId, function (result)
					{
						$('#all b').text(result.Count);
					});
				}
			});
		}
		else
		{
			//登录按钮
			$('#login').css('display', 'block').click(function()
			{
				if (document.domain == 'ww1.alibaza.com' || document.domain == 'ww2.alibaza.com')
					wx.miniProgram.navigateTo({url:'/pages/alibaza/login?ref=' + encodeURIComponent(window.location.href) + '&siteName=' + encodeURIComponent(page.data('siteName'))});
				else
					$(this).attr('href', getPlatformUrl() + 'user/login.html' + (_btoE ? '?btoe=1' : ''));
			});
		}
	})();
	//#endregion
}

//教师中心 - 申请
function TeacherApply(page)
{
	var __id;

	//#region 初始化
	(function ()
	{
		//未登录
		if (!isLogin())
		{
			if (document.domain == 'ww1.alibaza.com' || document.domain == 'ww2.alibaza.com')
				wx.miniProgram.navigateTo({url:'/pages/alibaza/login?ref=' + encodeURIComponent(window.location.href) + '&siteName=' + encodeURIComponent(page.data('siteName'))});
			else
				$(this).attr('href', getPlatformUrl() + 'user/login.html' + (_btoE ? '?btoe=1' : ''));
			
			return;
		}

		var form = $('form', page)[0];
		$.getJSON(page.data('path'), function (result)
		{
			if (result.agentId)
				window.location.replace(page.data('indexPath'));

			__id = result.id;
			form.Name.value = result.name;
			form.Mobile.value = result.mobile;
			form.Head.value = result.head;

			//事件绑定
			$(form).submit(onSubmitClick);
		});
	})();
	//#endregion

	function onSubmitClick()
	{
		if (this.Name.value == '')
		{
			ali.toast(page.data('nameEmpty'));
			return false;
		}

		if (!this.Mobile.value.match(/^\d{11}$/))
		{
			ali.toast(page.data('mobileIncorrect'));
			return false;
		}

		ali.working(ali.dict('working'));

		//准备数据
		var data = 'Name=' + encodeURIComponent($.trim(this.Name.value));
		data += '&Mobile=' + this.Mobile.value;
		data += '&Head=' + encodeURIComponent(this.Head.value);
		if (__id)//已存在
		{
			$.ajax(
			{
				url: '/alicms.aspx?Lang=' + ali.lang + '&Mark=Company&Object=Contact&Operation=Modify&ID=' + __id,
				data: data,
				type: 'POST',
				error: function()
				{
					ali.working();
					ali.toast(ali.dict('operation_fail'));
				},
				success: function()
				{
					addTeacher();
				}
			});
		}
		else//新增
		{
			data += '&CompanyID=' + page.data('companyId');

			$.ajax(
			{
				url: '/alicms.aspx?Lang=' + ali.lang + '&Mark=Company&Object=Contact&Operation=Add',
				data: data,
				type: 'POST',
				error: function()
				{
					ali.working();
					ali.toast(ali.dict('operation_fail'));
				},
				success: function()
				{
					addTeacher();
				}
			});
		}

		return false;
	}

	function addTeacher()
	{
		//准备数据
		var form = $('form', page)[0];
		var data = 'Name=' + encodeURIComponent($.trim(form.Name.value));
		data += '&UserID=' + ali.util.cookie('UserID');
		data += '&UserName=' + ali.util.cookie('UserName');
		data += '&SubInstanceID=' + page.data('subInstanceId');

		$.ajax(
		{
			url: '/alicms.aspx?Lang=' + ali.lang + '&Mark=Course&Object=Teacher&Operation=Add',
			data: data,
			type: 'POST',
			error: function()
			{
				ali.working();
				ali.toast(ali.dict('operation_fail'));
			},
			success: function()
			{
				ali.working();
				ali.toast(ali.dict('operation_success'), function(){window.location.replace(page.data('indexPath'));});
			}
		});
	}
}

//教师中心 - 订单统计
function TeacherStat(page)
{
	//#region 初始化
	(function ()
	{
		$('[name=IsAll],[name=IsFinished],[name=IsArchived],[name=IsCanceled],[name=IsPayed]').click(refresh);

		refresh();
	})();
	//#endregion

	function refresh()
	{
		var now = new Date();

		var path = '/alicms.aspx?Lang=' + ali.lang + '&Mark=Course&Object=Order&SubInstanceID=' + page.data('subInstanceId') + '&TeacherID=' + page.data('teacherId');
		if (!$('[name=IsAll]').prop('checked'))
		{
			path += '&IsFinished=' + $('[name=IsFinished]').prop('checked');
			path += '&IsArchived=' + $('[name=IsArchived]').prop('checked');
			path += '&IsCanceled=' + $('[name=IsCanceled]').prop('checked');
		}

		var isPayed = $('[name=IsPayed]:checked').val();
		if (isPayed != '')
			path += '&IsPayed=' + isPayed;

		//今日合计
		var start = encodeURIComponent(ali.util.formatDate(now, 'yyyy-MM-dd 00:00:00'));
		var end = encodeURIComponent(ali.util.formatDate(now, 'yyyy-MM-dd 23:59:59'));
		$.getJSON(path + '&Operation=SubSite_Teacher_StatOne&Start=' + start + '&End=' + end, function (result)
		{
			$('#today').text(result.Count);
		});

		//今日统计
		$.getJSON(path + '&Operation=SubSite_Teacher_StatHourly&Start=' + start + '&End=' + end, function (result)
		{
			var html = '';
			for (var i in result)
			{
				html += '<tr><th>' + result[i].Hour + '</th><td>' + result[i].Count + '</td></tr>';
			}
			$('#teacher-stat-today tbody').html(html);
		});

		//本月合计
		start = encodeURIComponent(ali.util.formatDate(now, 'yyyy-MM-01 00:00:00'));
		end = encodeURIComponent(ali.util.formatDate(now, 'yyyy-MM-dd 23:59:59'));
		$.getJSON(path + '&Operation=SubSite_Teacher_StatOne&Start=' + start + '&End=' + end, function (result)
		{
			$('#month').text(result.Count);
		});

		//本月统计
		$.getJSON(path + '&Operation=SubSite_Teacher_StatDaily&Start=' + start + '&End=' + end, function (result)
		{
			var html = '';
			for (var i in result)
			{
				html += '<tr><th>' + result[i].Day.substr(8) + '</th><td>' + result[i].Count + '</td></tr>';
			}
			$('#teacher-stat-month tbody').html(html);
		});

		//本年合计
		start = encodeURIComponent(ali.util.formatDate(now, 'yyyy-01-01 00:00:00'));
		end = encodeURIComponent(ali.util.formatDate(now, 'yyyy-MM-dd 23:59:59'));
		$.getJSON(path + '&Operation=SubSite_Teacher_StatOne&Start=' + start + '&End=' + end, function (result)
		{
			$('#year').text(result.Count);
		});

		//本年统计
		$.getJSON(path + '&Operation=SubSite_Teacher_StatMonthly&Start=' + start + '&End=' + end, function (result)
		{
			var html = '';
			for (var i in result)
			{
				html += '<tr><th>' + result[i].Month.substr(5) + '</th><td>' + result[i].Count + '</td></tr>';
			}
			$('#teacher-stat-year tbody').html(html);
		});

		//全部订单
		$.getJSON(path + '&Operation=SubSite_Teacher_StatOne', function (result)
		{
			$('#all').text(result.Count);
		});
	}
}

//教师中心 - 我的订单
function TeacherOrderList(page)
{
	var __page = 1,
		__pageSize = 15,
		__isEnd = false,
		__isLoading = true,
		__list = $('#teacher-order-list-list', page);

	//#region 初始化
	(function ()
	{
		//搜索
		$('.titlebar form', page).submit(onSearchSubmit);

		//内容滚动
		__list.scroll(onListScroll);

		//
		load(1);
	})();
	//#endregion

	function onSearchSubmit()
	{
		load(1);
		return false;
	}

	function load(pageNumber)
	{
		__isLoading = true;
		__page = pageNumber;

		if (__page == 1)
			$('.more', page).text(_btoE ? bToE(page.data('loading')) : page.data('loading')).siblings().remove();
		
		var condition = '?Page=' + __page + '&PageSize=' + __pageSize + '&TeacherID=' + page.data('teacherId') + '&Keyword=' + encodeURIComponent($('.titlebar input', page).val());
		$.get(page.data('path') + condition, function (result)
		{
			result = $.trim(result);

			if (result != '')
				$('.more', page).before(_btoE ? bToE(result) : result);

			var matches = result.match(/<a/g);
			if (matches == null || matches.length < __pageSize)
			{
				$('.more', page).text(_btoE ? bToE(page.data('hasReadAll')) : page.data('hasReadAll'));
				__isEnd = true;
			}
			else
			{
				__isEnd = false;
			}
			
			__isLoading = false;
		});
	}

	function onListScroll()
	{
		if (__isEnd || __isLoading)
			return;

		if (__list[0].scrollHeight - __list[0].clientHeight < this.scrollTop + 10)
		{
			load(__page + 1);
		}
	}
}

//教师中心 - 详情
function TeacherView(page)
{
	//#region 初始化
	(function ()
	{
		//滚动时，tab2-bar浮动或固定
		$('.tab2-bar a').click(onTab2BarClick);
		var tab2Top = $('.tab2-bar').offset().top;
	    $('.tab1-body').scroll(function ()
	    {
	    	var scrollTop = $(this).scrollTop();
			if (scrollTop >= tab2Top)
				$('.tab2-content').css('overflow-y', 'auto');
			else
				$('.tab2-content').css('overflow-y', 'hidden');
	    });
		
		//增加人气
		$.post('/alicms.aspx?Lang=' + ali.lang + '&Mark=Course&Object=Teacher&Operation=IncrementHitCount&ID=' + page.data('id'), {});
	})();
	//#endregion

	function onTab2BarClick()
	{
		if ($(this).hasClass('active'))
			return;

		$(this).addClass('active').siblings().removeClass('active');

		var index = $(this).parent().children().index(this);
		var content = $(this).parent().next().children().eq(index);
		content.addClass('active').siblings().removeClass('active');
	}
}

//用户中心 - 首页
function UserIndex(page)
{
	//#region 初始化
	(function ()
	{
	    //存储分享者
		saveDistributer();

		if (isLogin())
		{
			//用户名
			$('#user-index-head label', page).text(ali.util.cookie('UserName')).show();
			
			//头像
			$.getJSON(page.data('path'), function (result)
			{
				$('#user-index-head img', page).attr('src', result.head.replace('http://', 'https://'));
	
				//用昵称显示
				if (result.Nickname != '')
					$('#user-index-head label', page).text(result.Nickname);

				//是否会员
				if (result.isMember)
				{
					var p = $('#user-index-head p').show();
					if (result.days > 0)
					{
						p.find('em').text(result.levelName);
						p.find('b').text(result.days);
						p.next().css('display', 'block');
					}
					else
					{
						p.remove();
						$('#apply').css('display', 'block');
					}
				}
				else if (result.levels > 0)
				{
					$('#apply').css('display', 'block');
				}
			});

			//显示功能
			$('.user-index-section', page).show();
			$('#logout').css('display', 'block');
		}
		else
		{
			//登录按钮
			$('#user-index-head a:eq(0)', page).css('display', 'block').click(function(){login(page.data('wxppAppId'));});
		}
	})();
	//#endregion
}

//用户中心 - 微信一键登录
function UserWxLogin(page)
{
	//#region 初始化
	(function ()
	{
		fastLogin();
	})();
	//#endregion
	
	function fastLogin()
	{
		ali.working(ali.dict('working'));

		var url = page.data('ref');
		if (!url)
			url = page.data('userIndexPath');

		var data = 'Code=' + page.data('code');
		
		$.ajax(
		{
			url: '/alicms.aspx?Lang=' + ali.lang + '&Mark=User&Object=User&Operation=LoginByWxpp',
			data: data,
			type: 'POST',
			success: function(result)
			{
				result = JSON.parse(result);
				if (result.error != 0)
				{
					ali.toast(ali.dict('operation_fail'));
				}
				else
				{
					window.location.replace(url);
				}
			},
			error: function()
			{
				ali.working();
				ali.toast(ali.dict('operation_fail'));
			}
		});
	}
}

//修改资料
function Material(page)
{
	//#region 初始化
	(function ()
	{
		$('#form>div>div:eq(0)').click(function(){copy($('p', this).text());});
		$('#form').submit(onSubmit);
	})();
	//#endregion
	
	function copy(text)
	{
		var t = $('<textarea/>').appendTo('body');
		t.val(text);
		t[0].select();
		
		try
		{
			document.execCommand('copy');
			ali.toast(text);
		}
		catch (e)
		{
			ali.toast('复制失败！');
		}
	
		t.remove();
	}

	function onSubmit()
	{
		var data = 'RealName=' + encodeURIComponent(this.RealName.value);
		data += '&Sex=' + $('[name=Sex]:checked', this).val();
		data += '&Mobile=' + this.Mobile.value;

		ali.working(ali.dict('working'));

		var form = this;

		$.ajax(
		{
			url: '/alicms.aspx?Lang=' + ali.lang + '&Mark=User&Object=User&Operation=Modify&ID=' + page.data('id'),
			data: data,
			type: 'POST',
			success: function()
			{
				ali.working();
				ali.toast(ali.dict('operation_success'), function(){$('.back').click();});
			},
			error: function()
			{
				ali.working();
				ali.toast(ali.dict('operation_fail'));
			}
		});

		return false;
	}
}

//用户中心 - 我的收藏
function UserCollectList(page)
{
	//#region 初始化
	(function ()
	{
		$('.list8').on('click', 'del', onDeleteClick);
	})();
	//#endregion

	function onDeleteClick()
	{
		var row = $(this).closest('li');
	
		ali.working(ali.dict('working'));

		$.ajax(
		{
			url: '/alicms.aspx?Lang=' + ali.lang + '&Mark=Course&Object=Collect&Operation=Delete&ID=' + row.data('id'),
			data: {},
			type: 'POST',
			error: function ()
			{
				ali.toast(ali.dict('operation_fail'));
				ali.working();
			},
			success: function ()
			{
				row.remove();
				ali.toast(ali.dict('operation_success'));
				ali.working();
			}
		});
	}
}

//会员中心 - 首页
function MemberIndex(page)
{
	//#region 初始化
	(function ()
	{
		$.getJSON(page.data('path'), function (result)
		{
			if (!result.isMember)
			{
				location.replace(page.data('userIndexPath'));
				return;
			}

			$('header img').attr('src', result.head);
			$('header h1').text(result.name);
			$('header h2').text(result.levelName + ' : ' + result.no);
			$('#balance').text(result.balance.toFixed(2));
			$('#today').text(result.today.toFixed(2));
			$('#month').text(result.month.toFixed(2));
		});
	})();
	//#endregion
}

//会员中心 - 开通代理
function MemberApply(page)
{
	var __userInnerId,
		__userRealName,
		__userMobile,
		__userNickname,
		__userHead,
		__distributerId,
		__distributerName,
		__distributerNickname,
		__distributerHead,
		__distributerIsAgent,
		__agentCommision,
		__paymentId;

	//#region 初始化
	(function ()
	{
	    //存储分享者
	    saveDistributer();

		//强制登陆
		if (!isLogin())
		{
			login(page.data('wxppAppId'));
			return;
		}

		var path = page.data('path');
		var hasDistributer = ali.util.cookie('DistributerID') != '' && ali.util.cookie('UserID') != ali.util.cookie('DistributerID');
		if (hasDistributer)
			path += '?DistributerID=' + ali.util.cookie('DistributerID');
		$.getJSON(path, function (result)
		{
			//检查是否已经是会员
			if (result.isMemberAlready)
			{
				ali.alert(page.data('alreadyMember'), {modal: true, onClose: function()
				{
					window.location.replace(page.data('memberIndexPath'));
				}});
				return;
			}

			//用户信息
			__userInnerId = result.userInnerId;
			__userRealName = result.userRealName;
			__userMobile = result.userMobile;
			__userNickname = result.userNickname;
			__userHead = result.userHead;

			//初始化字段
			var form = $('form', page)[0];
			form.Name.value = result.userRealName;
			form.Mobile.value = result.userMobile;

			//代理
			if (result.distributerId)
			{
				__distributerId = result.distributerId;
				__distributerName = result.distributerName;
				__distributerNickname = result.distributerNickname;
				__distributerHead = result.distributerHead;
				__distributerIsAgent = result.distributerIsAgent;
				__agentCommision = result.agentCommision;
				form.Parent.value = __distributerNickname;
			}

			//支付方式
			__paymentId = result.paymentId;

			//处理无效html编辑器代码		
			$('.agreement', page).each(function()
			{
				var h = $(this).html();
				$(this).html(htmlDecode(h));
			});

			//事件绑定
			ali.combo($('[data-ali-widget=combo]', form));
			$(form).submit(onSubmitClick);
			$('[name=LevelID]', form).change(onLevelChange).change();

			//初始化微信
			initWx({ imgUrl: page.data('logo') });
		});
	})();
	//#endregion
	
	function htmlDecode(str)
	{  
         var s = '';
         if(str.length == 0) return '';
         s = str.replace(/&amp;/g,'&');
         s = s.replace(/&lt;/g,'<');
         s = s.replace(/&gt;/g,'>');
         s = s.replace(/&nbsp;/g,' ');
         s = s.replace(/&#39;/g,"\'");
         s = s.replace(/&quot;/g,"\"");
         return s;
	}
	
	function onLevelChange()
	{
		var i = this.selectedIndex - 1;
		$('.agreement', page).hide();
		if (i >= 0)
			$('.agreement:eq(' + i + ')', page).show();
		
		var fee = $('option:selected', this).data('fee');
		$('.block7-footer em').text(fee);
	}

	function onSubmitClick()
	{
		if ($(this).hasClass('disabled'))
			return false;
		$(this).addClass('disabled');

		if (this.Name.value == '')
		{
			ali.toast(page.data('nameEmpty'));
			$(this).removeClass('disabled');
			return false;
		}

		if (!this.Mobile.value.match(/^\d{11}$/))
		{
			ali.toast(page.data('mobileIncorrect'));
			$(this).removeClass('disabled');
			return false;
		}

		if (this.LevelID.value == '')
		{
			ali.toast(page.data('levelEmpty'));
			$(this).removeClass('disabled');
			return false;
		}

		ali.working(ali.dict('working'));

		//准备数据
		if (this.Name.value != __userRealName || this.Mobile.value != __userMobile)
		{
			var data = 'RealName=' + encodeURIComponent($.trim(this.Name.value));
			data += '&Mobile=' + this.Mobile.value;
			$.ajax(
			{
				url: '/alicms.aspx?Lang=' + ali.lang + '&Mark=User&Object=User&Operation=Modify&ID=' + __userInnerId,
				data: data,
				type: 'POST',
				success: function()
				{
				},
				error: function()
				{
				}
			});
		}
	
		var form = $('form', page)[0];
		var level = $(':selected', form.LevelID);
		var fee = parseFloat(level.data('fee'));

		var data = 'LevelID=' + level.val();
		data += '&TimeUnit=' + level.data('timeUnit');
		data += '&TimeAmount=' + level.data('timeAmount');
		data += '&UserID=' + ali.util.cookie('UserID');
		data += '&UserName=' + ali.util.cookie('UserName');
		data += '&UserNickname=' + __userNickname;
		data += '&UserHead=' + __userHead;

		if (__distributerId)
		{
			data += '&DistributerID=' + __distributerId;
			data += '&DistributerName=' + __distributerName;
			data += '&DistributerNickname=' + encodeURIComponent(__distributerNickname);
			data += '&DistributerHead=' + encodeURIComponent(__distributerHead);
			if (__distributerIsAgent)
			{
				data += '&DistributerIsAgent=true';
				data += '&AgentCommision=' + (fee * __agentCommision / 100).toFixed(2);
			}
		}

		data += '&Price=' + fee;
		data += '&Sum=' + fee;

		$.ajax(
		{
			url: '/alicms.aspx?Lang=' + ali.lang + '&Mark=Course&Object=MemberOrder&Operation=Add',
			data: data,
			type: 'POST',
			error: function()
			{
				ali.working();
				ali.toast(ali.dict('operation_fail'), function()
				{
					window.location.reload();
				});
			},
			success: function(guid)
			{
				if (fee > 0)
				{
					//准备数据
					var data = 'Title=' + encodeURIComponent(document.title);
					data += '&Amount=' + fee;
					data += '&PaymentID=' + __paymentId;
					data += '&ReturnUrl=' + encodeURIComponent(page.data('payReturnUrlPath'));

					$.ajax(
					{
						url: '/alicms.aspx?Lang=' + ali.lang + '&Mark=Course&Object=MemberOrder&Operation=OnlinePayRequest&ID=' + guid,
						data: data,
						type: 'POST',
						error: function ()
						{
							ali.toast(ali.dict('operation_fail'));
							ali.working();
						},
						success: function (data)
						{
							$('body').append('<div style="display:none">' + data + '</div>').find('form:last').submit();
						}
					});
				}
				else
				{
					window.location.replace(page.data('memberIndexPath'));
				}
			}
		});

		return false;
	}
}

//会员中心 - 支付结果
function MemberPayReturnUrl(page)
{
	//#region 初始化
	(function ()
	{
		//判断是否出错
		var params = page.data('params');
		if (params.error)
		{
			alert(params.errmsg);
			window.location.replace(page.data('memberIndexPath'));
			return;
		}

		//微信JS Api准备事件
		if (typeof(WeixinJSBridge) == 'undefined')
		{
			if (document.addEventListener)
			{
				document.addEventListener('WeixinJSBridgeReady', onWeixinJSBridgeReady, false);
			}
			else if (document.attachEvent)
			{
				document.attachEvent('WeixinJSBridgeReady', onWeixinJSBridgeReady);
				document.attachEvent('onWeixinJSBridgeReady', onWeixinJSBridgeReady);
			}
		}
		else
		{
			onWeixinJSBridgeReady();
		}
	})();
	//#endregion

	function onWeixinJSBridgeReady()
	{
		WeixinJSBridge.invoke('getBrandWCPayRequest', page.data('params'), function(result)
		{
			if (result.errMsg && result.errMsg.indexOf('fail') != -1)
			{
				alert(JSON.stringify(result) + '\r\n' + JSON.stringify(page.data('params')));
				window.location.replace(page.data('memberIndexPath'));
			}

			if (result.err_msg.indexOf('ok') != -1)
			{
				window.location.replace(page.data('memberIndexPath'));
			}
			else if (result.err_msg.indexOf('cancel') != -1)
			{
				window.location.replace(page.data('memberIndexPath'));
			}
			else
			{
				alert(JSON.stringify(result) + '\r\n' + JSON.stringify(page.data('params')));
				window.location.replace(page.data('memberIndexPath'));
			}
		});
	}
}

//会员中心 - 我的下线
function MemberChildren(page)
{
	//#region 初始化
	(function ()
	{
		//计算孙级代理总数
		var n = 0;
		$('ul:gt(0)', page).each(function () { n += $(this).children().length; });
		$('#agent-children-body>p>span:eq(1)').text(n);
	})();
	//#endregion
}

//会员中心 - 课程订单
function MemberOrderList(page)
{
	var __page = 1,
		__pageSize = 15,
		__isEnd = false,
		__isLoading = true,
		__list = $('.member-order-list', page);

	//#region 初始化
	(function ()
	{
		//搜索
		$('.titlebar form', page).submit(onSearchSubmit);

		//内容滚动
		__list.scroll(onListScroll);

		//
		load(1);
	})();
	//#endregion

	function onSearchSubmit()
	{
		load(1);
		return false;
	}

	function load(pageNumber)
	{
		__isLoading = true;
		__page = pageNumber;

		if (__page == 1)
			$('.more', page).text(page.data('loading')).siblings().remove();
		
		var condition = '?Page=' + __page + '&PageSize=' + __pageSize + '&Keyword=' + encodeURIComponent($('.titlebar input', page).val());
		$.get(page.data('getList') + condition, function (result)
		{
			result = $.trim(result);

			if (result != '')
				$('.more', page).before(result);

			var matches = result.match(/<a/g);
			if (matches == null || matches.length < __pageSize)
			{
				$('.more', page).text(page.data('hasReadAll'));
				__isEnd = true;
			}
			else
			{
				__isEnd = false;
			}
			
			__isLoading = false;
		});
	}

	function onListScroll()
	{
		if (__isEnd || __isLoading)
			return;

		if (__list[0].scrollHeight - __list[0].clientHeight < this.scrollTop + 10)
		{
			load(__page + 1);
		}
	}
}

//会员中心 - 会员订单
function MemberMemberOrderList(page)
{
	var __page = 1,
		__pageSize = 15,
		__isEnd = false,
		__isLoading = true,
		__list = $('.member-member-order-list', page);

	//#region 初始化
	(function ()
	{
		//搜索
		$('.titlebar form', page).submit(onSearchSubmit);

		//内容滚动
		__list.scroll(onListScroll);

		//
		load(1);
	})();
	//#endregion

	function onSearchSubmit()
	{
		load(1);
		return false;
	}

	function load(pageNumber)
	{
		__isLoading = true;
		__page = pageNumber;

		if (__page == 1)
			$('.more', page).text(page.data('loading')).siblings().remove();
		
		var condition = '?Page=' + __page + '&PageSize=' + __pageSize + '&Keyword=' + encodeURIComponent($('.titlebar input', page).val());
		$.get(page.data('getList') + condition, function (result)
		{
			result = $.trim(result);

			if (result != '')
				$('.more', page).before(result);

			var matches = result.match(/<a/g);
			if (matches == null || matches.length < __pageSize)
			{
				$('.more', page).text(page.data('hasReadAll'));
				__isEnd = true;
			}
			else
			{
				__isEnd = false;
			}
			
			__isLoading = false;
		});
	}

	function onListScroll()
	{
		if (__isEnd || __isLoading)
			return;

		if (__list[0].scrollHeight - __list[0].clientHeight < this.scrollTop + 10)
		{
			load(__page + 1);
		}
	}
}

//会员中心 - 我的钱包
function MemberBalance(page)
{
	//#region 初始化
	(function ()
	{
		$.getJSON(page.data('path'), function (result)
		{
			var body = $('#body');
			for (var i in result)
			{
				var month = $('#' + result[i].month);
				if (month.length == 0)
				{
					month = $('<div id="' + result[i].month + '"><h1>' + result[i].month + '</h1></div>');
					body.append(month);
				}

				var day = $('#' + result[i].month + '-' + result[i].day, month);
				if (day.length == 0)
				{
					day = $('<div id="' + result[i].month + '-' + result[i].day + '"><h2>' + result[i].day + '</h2><ul></ul></div>');
					month.append(day);
				}

				$('ul', day).append('<li><a><label>' + result[i].typeName + '</label><span>' + result[i].hour + '</span><b><em>' + result[i].amount + '</em>' + (result[i].frozen == '' ? '' : '<i>' + result[i].frozen + '</i>') + '</b></a></li>');
			}
		});
	})();
	//#endregion	
}

(function()
{
	var page = $('.page');

	//ajax提交时，显示工作中
	$(document).ajaxStart(function(){if(!_silent)ali.working(ali.dict('working'));}).ajaxStop(function(){if(!_silent)ali.working();});

	//处理back
	page.on('click', '.back', function()
	{
		if ($(this).attr('href'))
			return;

		if (history.length > 1)
		{
			history.back();
		}
		else
		{
			window.location = '/';
		}
	});
		
	//
	var debug = true;
	if (!debug && location.pathname != '/' && navigator.platform.indexOf('iPhone') == -1 && navigator.platform.indexOf('iPad') == -1 && (navigator.platform.indexOf('Linux') == -1 || navigator.userAgent.indexOf('Android') == -1))
		window.location.href = '/';

	switch (page.attr('id'))
	{
		case 'index':
			Index(page);
			break;
		case 'course-list':
			CourseList(page);
			break;
		case 'course-view':
			CourseView(page);
			break;
		case 'lesson-text':
			LessonText(page);
			break;
		case 'course-pay-return-url':
			CoursePayReturnUrl(page);
			break;
		case 'teacher-index':
			TeacherIndex(page);
			break;
		case 'teacher-apply':
			TeacherApply(page);
			break;
		case 'teacher-stat':
			TeacherStat(page);
			break;
		case 'teacher-order-list':
			TeacherOrderList(page);
			break;
		case 'teacher-view':
			TeacherView(page);
			break;
		case 'user-index':
			UserIndex(page);
			break;
		case 'material':
			Material(page);
			break;
		case 'user-wx-login':
			UserWxLogin(page);
			break;
		case 'user-collect-list':
			UserCollectList(page);
			break;
		case 'member-index':
			MemberIndex(page);
			break;
		case 'member-apply':
			MemberApply(page);
			break;
		case 'member-pay-return-url':
			MemberPayReturnUrl(page);
			break;
		case 'member-order-list':
			MemberOrderList(page);
			break;
		case 'member-member-order-list':
			MemberMemberOrderList(page);
			break;
		case 'member-balance':
			MemberBalance(page);
			break;
	}
})();

